﻿using RimWorld;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Verse;

namespace RimZombieGirl
{
    public class StorytellerCompProperties_CurseRaid : StorytellerCompProperties
    {
        // 基础平均间隔（天），用来做曲线的基准
        public float baseMTBDays = 10f;

        // 曲线：输入是诅咒值，输出是 mtbDays 的修正倍率
        public SimpleCurve mtbDaysFactorByCurse;

        public StorytellerCompProperties_CurseRaid()
        {
            this.compClass = typeof(StorytellerComp_CurseRaid);
        }
    }

    public class StorytellerComp_CurseRaid : StorytellerComp
    {
        private StorytellerCompProperties_CurseRaid Props => (StorytellerCompProperties_CurseRaid)this.props;

        private IncidentDef cachedIncident;

        public override IEnumerable<FiringIncident> MakeIntervalIncidents(IIncidentTarget target)
        {
            Map map = target as Map;
            if (map == null) yield break;

            var comp = map.GetComponent<MapComponent_Curse>();
            if (comp == null) yield break;

            float curse = comp.currentCurseValue;

            // 诅咒为0时不触发
            if (curse <= 0f)
                yield break;

            // 曲线计算
            float factor = 1f;
            if (Props.mtbDaysFactorByCurse != null)
            {
                factor = Props.mtbDaysFactorByCurse.Evaluate(curse);
            }

            float mtbDays = Props.baseMTBDays * factor;
            mtbDays = Mathf.Max(0.2f, mtbDays);

            if (Rand.MTBEventOccurs(mtbDays, 60000f, 1000f))
            {
                if (cachedIncident == null)
                {
                    cachedIncident = DefDatabase<IncidentDef>.AllDefs
                        .FirstOrDefault(d => d.tags != null && d.tags.Contains("RI_CurseRaid"));
                }

                if (cachedIncident != null)
                {
                    IncidentParms parms = GenerateParms(cachedIncident.category, target);
                    if (cachedIncident.Worker.CanFireNow(parms))
                    {
                        yield return new FiringIncident(cachedIncident, this, parms);
                    }
                }
            }
        }

    }
}
